package com.dongdong.bookstore.module.cms.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dongdong.bookstore.common.api.CommonPage;
import com.dongdong.bookstore.common.api.ResultData;
import com.dongdong.bookstore.common.api.ReturnCode;
import com.dongdong.bookstore.common.exception.ApiException;
import com.dongdong.bookstore.common.exception.Asserts;
import com.dongdong.bookstore.module.ams.viewmodel.ArticleAddParam;
import com.dongdong.bookstore.module.cms.model.User;
import com.dongdong.bookstore.module.cms.service.UserService;
import com.dongdong.bookstore.module.cms.viewmodel.UpdateUserParam;
import com.dongdong.bookstore.module.cms.viewmodel.UpdateUserPasswordParam;
import com.dongdong.bookstore.module.cms.viewmodel.UserLoginParam;
import com.dongdong.bookstore.module.cms.viewmodel.UserRegistParam;

import com.dongdong.bookstore.module.ums.model.Admin;
import com.dongdong.bookstore.module.ums.model.Menu;
import com.dongdong.bookstore.module.ums.model.Role;
import com.dongdong.bookstore.module.ums.viewmodel.UpdateAdminPasswordParam;
import com.dongdong.bookstore.security.model.UserCategory;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 会员表 前端控制器
 * </p>
 *
 * @author chiangkai
 * @since 2021-10-27
 */
@Api(tags = "用户模块")
@RestController
@RequestMapping("/cms/user")
public class UserController {

    @Value("${jwt.tokenHeader}")
    private String tokenHeader;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Autowired
    private UserService userService;

    @Value("${spring.profiles.active}")
    private String ENV;

    @ApiOperation("注册用户")
    @PostMapping("/register")
    public ResultData<User> register(@RequestBody @Validated UserRegistParam param) {
        User user = userService.userRegister(param);
        return ResultData.ok("注册成功", user);
    }

    @ApiOperation("输入用户名判断用户存在")
    @PostMapping("/judgeAdminExistByUsername")
    public String judgeUserExistByUsername(@RequestParam(value = "username") String username) {
        userService.judgeAdminExistByUsername(username);
        return "用户名可注册";
    }

    @ApiOperation("输入电话判断用户存在")
    @PostMapping("/judgeAdminExistByTel")
    public String judgeUserExistByTel(@RequestParam(value = "tel") String tel) {
        userService.judgeAdminExistByTel(tel);
        return "电话可注册";
    }

    @ApiOperation("输入邮箱判断用户存在")
    @PostMapping("/judgeAdminExistByEmail")
    public String judgeUserExistByEmail(@RequestParam(value = "email") String email) {
        userService.judgeAdminExistByEmail(email);
        return "邮箱可注册";
    }

    @ApiOperation("用户登录操作")
    @PostMapping("/login")
    public Map<String, String> login(@RequestBody UserLoginParam userLoginParam) {
        String token = userService.login(userLoginParam);

        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("tokenHead", UserCategory.VIP.ordinal() + tokenHead);
        if (ENV.equals("dev")) {
            map.put("allToken", map.get("tokenHead") + map.get("token"));
        }
        return map;
    }



    @ApiOperation("用户口令刷新")
    @GetMapping("/reflashToken")
    public Map<String, String> reflashToken(HttpServletRequest request) {
        String source = request.getHeader(tokenHeader);
        String token = userService.refreshUserToken(source);
        HashMap<String, String> map = new HashMap<>();
        map.put("token", token);
        map.put("tokenHead", UserCategory.VIP.ordinal() + tokenHead);
        if (ENV.equals("dev")) {
            map.put("allToken", map.get("tokenHead") + map.get("token"));
        }
        return map;
    }

    @ApiOperation("用户获取个人信息")
    @GetMapping("/info")
    public Map<String, Object> getUserInfo(Principal principal) {

        if (principal == null) {
            throw new ApiException(ReturnCode.NO_TOKEN);
        }
        User user = userService.getUserByUsername(principal.getName().substring(principal.getName().indexOf(":") + 1));
        Map<String, Object> map = new HashMap<>();
        map.put("nickName", user.getNickName());
        map.put("id", user.getId());
        map.put("username", user.getUsername());
        map.put("headImg", user.getHeadImg());
        map.put("email", user.getEmail());
        map.put("tel", user.getTel());
        map.put("isDeleted", user.getDeleted());
        map.put("created_time", user.getCreatedTime());
        map.put("updated_time", user.getUpdatedTime());

        return map;
    }

    @ApiOperation("根据用户名或邮箱或手机号 或直接获取用户列表分页")
    @GetMapping("/list")
    public CommonPage<User> list(@RequestParam(value = "keyword", required = false) String keyword,
                                 @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                 @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        Page<User> userPage = userService.userList(keyword, pageSize, pageNum);
        return CommonPage.restPage(userPage);
    }

    @ApiOperation("通过用户ID获取用户信息")
    @GetMapping("/userInfo/{id}")
    public User getAdminById(@PathVariable("id") Long id) {
        return userService.getById(id);
    }

    @ApiOperation("修改指定用户信息基本信息（不包括密码）")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    public String update(@PathVariable Long id, @RequestBody UpdateUserParam updateUserParam) {
        boolean success = userService.userUpdateBaseInfo(id, updateUserParam);
        if (success) {
            return "更新成功";
        } else {
            Asserts.fail("更新失败");
        }
        return null;
    }

    @ApiOperation("通过旧密码更新密码接口")
    @PostMapping("/updatePassword")
    public String updatePassword(@Validated @RequestBody UpdateUserPasswordParam updateUserPasswordParam) {
        userService.updatePassword(updateUserPasswordParam);
        return "更新密码成功";
    }

    @ApiOperation("通过ID禁用用户账号")
    @GetMapping("/delUser/{id}")
    public String deleteUser(@PathVariable Long id) {
        boolean success = userService.userDel(id);
        if (success) {
            return "删除成功";
        } else {
            Asserts.fail("删除失败");
        }
        return null;
    }

    @ApiOperation("通过ID恢复用户账号")
    @GetMapping("/renewUser/{id}")
    public String renewUser(@PathVariable Long id) {
        boolean success = userService.userRenew(id);
        if (success) {
            return "恢复成功";
        } else {
            Asserts.fail("恢复失败");
        }
        return null;
    }


}
